import 'dart:convert';

import 'package:dio/dio.dart' as dio;
import 'package:flutter_axrjc/datasource/db/DBLightApi.dart';
import 'package:flutter_axrjc/datasource/db/bean/MyLightBean.dart';
import 'package:flutter_axrjc/datasource/network/api/UserApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/CheckLogBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/EventBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/GuideBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/LightBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/LightImagBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/LightTypeBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/LightTypeBean2.dart';
import 'package:flutter_axrjc/datasource/network/bean/LogDetailBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/MonthReportBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/ReportTopDataBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/VideoBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/datasource/network/request/network_service.dart';
import 'package:flutter_axrjc/main.dart';
import 'package:flutter_axrjc/util/DeviceInfoUtil.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class LightApi {
  static Future add({
    // required String brightnessAdjustment,
    // required String colorTemperatureAdjustment,
    required String fixtureBrand,
    required List<String> imgFile,
    required String fixtureModel,
    required String fixtureName,
    required String fixtureType,
    required String installationDate,
    required String remark,
  }) async {
    try {
      List<dio.MultipartFile> files = [];
      for (var element in imgFile) {
        files.add(await dio.MultipartFile.fromFile(element));
      }
      await NetworkService.post(
          url: 'app/proBaseCustomerFixtureSave.do',
          map: {
            // "brightnessAdjustment": brightnessAdjustment, //亮度调节：如果支持可调节亮度的灯具，可以记录当前亮度调节的数值或模式
            // "colorTemperatureAdjustment": colorTemperatureAdjustment, //如果支持可调节色温的灯具，可以记录当前色温调节的数值或模式
            "fixtureBrand": fixtureBrand,
            "imgFile": files,
            "fixtureModel": fixtureModel, //灯具型号
            "fixtureName": fixtureName, //灯具名R称
            "fixtureType": fixtureType, //0台灯、1吊灯、2射灯等
            "installationDate": installationDate,
            "remark": remark,
          },
          useFormData: true);
      eventBus.fire(EventBean(type: EventType.refreshMyLights, data: null));
      Get.back();
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }

  static Future<List<LightBean>> getAll({required int page}) async {
    var res = await NetworkService.post(
        url: "app/proBaseCustomerFixtureQuery.do",
        map: {"limit": "10", "offset": page},
        showLoading: false);
    await DBApi.deleteAll();
    var resList =
        res.getTypedList<LightBean>((map) => LightBean.fromJson(map)) ?? [];
    String userPhone = (await UserApi.getUser())?.customerInfo?.telPhone ?? '';
    await DBApi.putAll(resList
        .map((e) => myLightBean(
            userPhone: userPhone,
            lastDetectionTime: e.lastDetectionTime,
            fixtureId: e.fixtureId,
            fixtureName: e.fixtureName,
            fixtureBrand: e.fixtureBrand,
            fixtureModel: e.fixtureModel,
            fixtureImg: e.fixtureImg,
            fixtureType: e.fixtureType,
            installationDate: e.installationDate,
            fixtureStatus: e.fixtureStatus,
            brightnessAdjustment: e.brightnessAdjustment,
            colorTemperatureAdjustment: e.colorTemperatureAdjustment,
            remark: e.remark,
            ifBack: e.ifBack,
            customerId: e.customerId,
            sysCode: jsonEncode(e.sysCode?.toJson())))
        .toList());
    return resList;
  }

  static deleteLight(String s) async {
    await NetworkService.post(url: 'app/proDelBaseCustomerFixture/$s', map: {});
  }

  static getSingleDetail(String id) async {
    await NetworkService.post(
        url: "app/processBaseCustomerFixtureView/$id", map: {});
  }

  static Future<List<LightImagBean>> getImage(String id) async {
    var res = await NetworkService.post(
        url: "app/proBaseFileQuery.do",
        map: {"businessNo": id},
        showLoading: false);
    return res.getTypedList<LightImagBean>(
            (map) => LightImagBean.fromJson(map)) ??
        [];
  }

  static Future uploadLux(
      {required String checkOs,
      required String detectionAverageValue,
      required String detectionEndTime,
      required String detectionMaxValue,
      required String detectionMinValue,
      required String detectionStartTime,
      required String fixtureBrand,
      required String fixtureId,
      required String fixtureModel,
      required String fixtureType}) async {
    var device = await DeviceInfoUtil.getInfo();
    await NetworkService.post(
        url: "app/proBaseFixtureDetectionRecordsSave.do",
        map: {
          "checkOs": checkOs,
          "detectionAverageValue": detectionAverageValue,
          "detectionEndTime": detectionEndTime,
          "detectionMaxValue": detectionMaxValue,
          "detectionMinValue": detectionMinValue,
          "detectionStartTime": detectionStartTime,
          "fixtureBrand": fixtureBrand,
          "fixtureId": fixtureId,
          "fixtureModel": fixtureModel,
          "fixtureType": fixtureType,
          "mobileBrand": device.brand,
          "mobileModel": device.model,
        },
        loadingText: "正在上传");
  }

  static Future<List<CheckLogBean>> getLogList({
    required String queryStartTime,
    required String queryEndTime,
  }) async {
    var map = {
      "queryStartTime": queryStartTime,
      "queryEndTime": queryEndTime,
    };
    var res = await NetworkService.post(
        url: "app/fixtureDetRecordsQuery.do", map: map, loadingText: "查询中");
    return res
            .getTypedList<CheckLogBean>((map) => CheckLogBean.fromJson(map)) ??
        [];
  }

  static Future<List<CheckLogBean>> getLogListById({
    required String fixtureId,
  }) async {
    var map = {
      "fixtureId": fixtureId,
    };
    var res = await NetworkService.post(
        url: "app/fixtureDetRecordsQuery.do", map: map, loadingText: "查询中");
    return res
            .getTypedList<CheckLogBean>((map) => CheckLogBean.fromJson(map)) ??
        [];
  }

  static Future<String> getECharData(
      {required String queryTimeType, required String fixtureId}) async {
    var res = await NetworkService.postData(url: "app/getMonthReport", map: {
      "queryTimeType": queryTimeType,
      "fixtureId": fixtureId,
    });
    return '$res';
  }

  static Future<List<MonthReportBean>> getMonthReportList({
    required int page,
  }) async {
    var res = await NetworkService.post(
        url: 'app/proBaseMonthFixtureDetectionRecordsQuery.do',
        map: {
          "limit": "10",
          "offset": "$page",
        },
        showLoading: false);
    return res.getTypedList<MonthReportBean>(
            (map) => MonthReportBean.fromJson(map)) ??
        [];
  }

  static Future<ReportTopDataBean?> getReportTopData(String fixtureId) async {
    var res = await NetworkService.post(
        url: "app/getTopData", map: {"fixtureId": fixtureId});
    return res.getTypedData((map) => ReportTopDataBean.fromJson(map));
  }

  static Future setStatus(String remindId, String s) async {
    await NetworkService.post(
        url: '/app/proBaseRemindUpdate.do',
        map: {"remindId": remindId, "remindStatus": s});
  }

  static deleteNotice({required String key}) async {
    await NetworkService.post(url: 'app/proDelBaseRemind/$key', map: {});
  }

  static Future<List<LightTypeBean>> getAllType() async {
    var res = await NetworkService.post(
        url: 'app/getFixtureType', map: {}, showLoading: false);
    return res.getTypedList<LightTypeBean>(
            (map) => LightTypeBean.fromJson(map)) ??
        [];
  }

  static Future<List<LightBrandTypeBean>> getBrandType() async {
    var res = await NetworkService.post(
        url: 'app/listLampBrand.do', map: {}, showLoading: false);
    return res.getTypedList<LightBrandTypeBean>(
            (map) => LightBrandTypeBean.fromJson(map)) ??
        [];
  }

  static Future<LogDetailBean?> getLogDetail(
      {required String fixtureId, required String recordId}) async {
    var res = await NetworkService.post(
        url: 'app/processBaseFixtureDetectionRecordsView/$recordId', map: {});
    return res
        .getTypedData<LogDetailBean>((map) => LogDetailBean.fromJson(map));
  }

  static Future change({
    required String brightnessAdjustment,
    // required String colorTemperatureAdjustment,
    required String fixtureBrand,
    // required List<String> imgFile,
    required String fixtureModel,
    required String fixtureName,
    required String fixtureType,
    required String installationDate,
    required String remark,
    required String fixtureId,
  }) async {
    await NetworkService.post(url: 'app/proBaseCustomerFixtureUpdate.do', map: {
      "brightnessAdjustment":
          brightnessAdjustment, //亮度调节：如果支持可调节亮度的灯具，可以记录当前亮度调节的数值或模式
      // "colorTemperatureAdjustment": colorTemperatureAdjustment, //如果支持可调节色温的灯具，可以记录当前色温调节的数值或模式
      "fixtureBrand": fixtureBrand,
      // "imgFile": files,
      "fixtureModel": fixtureModel, //灯具型号
      "fixtureName": fixtureName, //灯具名R称
      "fixtureType": fixtureType, //0台灯、1吊灯、2射灯等
      "installationDate": installationDate,
      "remark": remark,
      "fixtureId": fixtureId,
    });
  }

  static deleteImgByFileNo(String ifUploadedNo) async {
    await NetworkService.post(url: "app/proDelBaseFile/$ifUploadedNo", map: {});
  }

  static addLightImage(List<String> localImageList, String businessNo) async {
    List<dio.MultipartFile> files = [];
    for (var element in localImageList) {
      files.add(await dio.MultipartFile.fromFile(element));
    }
    await NetworkService.post(
        url: "app/proBaseFileSave.do",
        map: {"imgFile": files, "businessNo": businessNo},
        useFormData: true);
  }

  static Future<String> getPreCheckMobile({required String fid}) async {
    var res =
        await NetworkService.post(url: 'app/preCheckMobile/$fid', map: {});
    return "${res.data}";
  }

  static Future<GuideBean?> getCheckGuide() async {
    var res = await NetworkService.post(url: 'app/loadGuideDetail.do', map: {});
    return res.getTypedData((map) => GuideBean.fromJson(map));
  }

  static Future<VideoBean?> getVideo({
    required String lampBrandCode, //品牌
    required String lampTypeId, //型号
  }) async {
    var res = await NetworkService.post(
        url: 'app/loadGuideVideo.do',
        map: {"lampBrandCode": lampBrandCode, "lampTypeId": lampTypeId});
    return res.getTypedData((map) => VideoBean.fromJson(map));
  }
}
